// 交互式学习界面组件

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FiVolume2, FiMic, FiStar, FiArrowLeft, FiRefreshCw, FiBookOpen } from 'react-icons/fi';
import { useApp } from '../contexts/AppContext';
import { speechService } from '../utils/speechService';
import { wordValidator } from '../utils/wordValidator';
import { aiService } from '../services/aiService';
import { Word, Hotspot } from '../types';
import { toast } from 'react-hot-toast';

const InteractiveLearning: React.FC = () => {
  const { state, setLearningMode, addWordToLearned, generateScene } = useApp();
  const [selectedHotspot, setSelectedHotspot] = useState<string | null>(null);
  const [wordDefinitions, setWordDefinitions] = useState<{ [key: string]: Word }>({});
  const [isRecording, setIsRecording] = useState(false);
  const [pronunciationResults, setPronunciationResults] = useState<{ [key: string]: number }>({});
  const [showDefinition, setShowDefinition] = useState(false);
  const [currentWord, setCurrentWord] = useState<string | null>(null);
  const [loadedSceneId, setLoadedSceneId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  // 初始化单词定义数据（使用 AI 服务）
  useEffect(() => {
    console.log('🎯 useEffect 触发，当前场景ID:', state.currentScene?.id, '已加载ID:', loadedSceneId, '正在加载:', isLoading);
    if (state.currentScene && state.currentScene.id !== loadedSceneId && !isLoading) {
      console.log('🚀 开始加载场景单词定义，场景ID:', state.currentScene.id);
      setLoadedSceneId(state.currentScene.id);
      setIsLoading(true);
      loadWordDefinitions(state.currentScene.words);
    } else if (state.currentScene?.id === loadedSceneId) {
      console.log('⏭️ 场景已加载，跳过重复请求');
    } else if (isLoading) {
      console.log('⏳ 正在加载中，跳过重复请求');
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.currentScene?.id, loadedSceneId, isLoading]); // 监听场景ID、已加载ID和加载状态

  // 加载单词定义
  const loadWordDefinitions = async (words: string[]) => {
    console.log('🔄 loadWordDefinitions 被调用，单词列表:', words);
    const definitions: { [key: string]: Word } = {};
    
    try {
      // 为每个单词获取定义
      for (const [index, word] of words.entries()) {
        try {
          console.log(`🔍 开始获取单词定义: ${word}`);
          // 尝试使用 AI 服务获取定义
          const aiDefinition = await aiService.getWordDefinition(word, state.language);
          console.log(`✅ 成功获取单词定义: ${word}`);
          
          definitions[word] = {
            id: `word-${index}`,
            text: word,
            definition: aiDefinition.definition,
            pronunciation: aiDefinition.pronunciation,
            partOfSpeech: aiDefinition.partOfSpeech,
            examples: aiDefinition.examples,
            difficulty: wordValidator.getWordDifficulty(word),
            learned: false,
            correctPronunciations: 0,
            totalAttempts: 0
          };
        } catch (error) {
          console.error(`Failed to get definition for ${word}:`, error);
          // 降级到默认定义
          definitions[word] = {
            id: `word-${index}`,
            text: word,
            definition: getWordDefinition(word),
            pronunciation: `/${getWordPronunciation(word)}/`,
            partOfSpeech: getPartOfSpeech(word),
            examples: getWordExamples(word),
            difficulty: wordValidator.getWordDifficulty(word),
            learned: false,
            correctPronunciations: 0,
            totalAttempts: 0
          };
        }
      }
      
      console.log('✅ 所有单词定义加载完成，设置状态');
      setWordDefinitions(definitions);
    } finally {
      setIsLoading(false); // 确保在完成或错误时都重置加载状态
      console.log('🏁 加载状态已重置');
    }
  };

  const getWordDefinition = (word: string): string => {
    const definitions: { [key: string]: string } = {
      'cat': '猫，一种小型的猴食性哺乳动物',
      'dog': '狗，一种家养的肉食性哺乳动物',
      'house': '房子，人们居住的建筑物',
      'car': '汽车，一种陆地交通工具',
      'book': '书，用于阅读或学习的印刷品',
      'water': '水，无色无味的透明液体',
      'tree': '树，一种高大的木本植物',
      'beautiful': '美丽的，让人感到愉悦的外观',
      'important': '重要的，具有重大意义或价值的',
      'understand': '理解，掌握某事的意义或重要性'
    };
    return definitions[word.toLowerCase()] || `${word} - 一个英语单词，请查询词典获取详细释义`;
  };

  // 模拟获取单词发音
  const getWordPronunciation = (word: string): string => {
    const pronunciations: { [key: string]: string } = {
      'cat': 'kæt',
      'dog': 'dɔːɡ',
      'house': 'haʊs',
      'car': 'kɑːr',
      'book': 'bʊk',
      'water': 'ˈwɔːtər',
      'tree': 'triː',
      'beautiful': 'ˈbjuːtɪfəl',
      'important': 'ɪmˈpɔːrtənt',
      'understand': 'ˌʌndərˈstænd'
    };
    return pronunciations[word.toLowerCase()] || word;
  };

  // 获取词性
  const getPartOfSpeech = (word: string): string => {
    const pos: { [key: string]: string } = {
      'cat': 'noun',
      'dog': 'noun', 
      'house': 'noun',
      'car': 'noun',
      'book': 'noun',
      'water': 'noun',
      'tree': 'noun',
      'beautiful': 'adjective',
      'important': 'adjective',
      'understand': 'verb'
    };
    return pos[word.toLowerCase()] || 'unknown';
  };

  // 获取例句
  const getWordExamples = (word: string): string[] => {
    const examples: { [key: string]: string[] } = {
      'cat': ['The cat is sleeping on the sofa.', 'I love my pet cat.'],
      'dog': ['The dog is running in the park.', 'Dogs are loyal animals.'],
      'house': ['This is a beautiful house.', 'I live in a small house.'],
      'car': ['My car is red.', 'We drove the car to work.'],
      'book': ['I\'m reading an interesting book.', 'Books contain knowledge.'],
      'water': ['Water is essential for life.', 'Please drink more water.'],
      'tree': ['The tree has green leaves.', 'Birds live in trees.'],
      'beautiful': ['She is very beautiful.', 'What a beautiful day!'],
      'important': ['Education is important.', 'This is an important decision.'],
      'understand': ['I understand the lesson.', 'Do you understand me?']
    };
    return examples[word.toLowerCase()] || [`This is an example with ${word}.`];
  };

  // 点击热点
  const handleHotspotClick = (hotspot: Hotspot) => {
    setSelectedHotspot(hotspot.id);
    setCurrentWord(hotspot.wordId);
    setShowDefinition(true);
    
    // 自动播放发音
    if (state.voiceEnabled) {
      playWordPronunciation(hotspot.wordId);
    }
  };

  // 播放单词发音
  const playWordPronunciation = async (word: string) => {
    try {
      await speechService.speak(word, { rate: 0.8 });
    } catch (error) {
      toast.error('发音播放失败');
    }
  };

  // 开始发音练习
  const startPronunciationPractice = async (word: string) => {
    if (!speechService.isSupported()) {
      toast.error('您的浏览器不支持语音识别');
      return;
    }

    // 防止重复点击
    if (isRecording) {
      console.log('🚫 已在录音中，忽略重复点击');
      return;
    }

    setIsRecording(true);
    console.log('🎤 开始发音练习:', word);
    
    try {
      // 添加超时处理
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('录音超时')), 10000); // 10秒超时
      });
      
      const speechPromise = speechService.startListening();
      
      const result = await Promise.race([speechPromise, timeoutPromise]) as any;
      console.log('🎯 发音识别结果:', result);
      
      const accuracy = speechService.calculatePronunciationAccuracy(word, result.transcript);
      
      setPronunciationResults(prev => ({ ...prev, [word]: accuracy }));
      
      // 更新单词统计
      if (wordDefinitions[word]) {
        const updatedWord = {
          ...wordDefinitions[word],
          totalAttempts: wordDefinitions[word].totalAttempts + 1,
          correctPronunciations: accuracy > 70 ? wordDefinitions[word].correctPronunciations + 1 : wordDefinitions[word].correctPronunciations
        };
        
        setWordDefinitions(prev => ({ ...prev, [word]: updatedWord }));
        
        if (accuracy > 70) {
          toast.success(`发音准确度: ${accuracy.toFixed(0)}%! 🎉`);
          if (accuracy > 90) {
            addWordToLearned(updatedWord);
          }
        } else {
          toast.error(`发音需要改进，准确度: ${accuracy.toFixed(0)}%`);
        }
      }
    } catch (error) {
      console.error('❌ 发音练习失败:', error);
      if (error.message === '录音超时') {
        toast.error('录音超时，请重试');
      } else {
        toast.error('发音识别失败，请重试');
      }
      
      // 确保停止语音识别
      speechService.stopListening();
    } finally {
      setIsRecording(false);
      console.log('🏁 发音练习结束');
    }
  };

  // 收藏场景
  const toggleFavorite = () => {
    if (state.currentScene) {
      // 这里可以添加收藏逻辑
      toast.success('场景已收藏到我的学习库！');
    }
  };

  // 重新生成场景
  const regenerateScene = async () => {
    if (state.currentScene) {
      await generateScene(state.currentScene.words);
    }
  };

  if (!state.currentScene) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center text-gray-500">
          <FiBookOpen size={48} className="mx-auto mb-4" />
          <p>没有当前学习场景</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-4 sm:p-6 space-y-4 sm:space-y-6">
      {/* 顶部导航 */}
      <motion.div 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between gap-2"
      >
        <button
          onClick={() => setLearningMode('input')}
          className="flex items-center gap-2 px-4 xs:px-5 py-2.5 bg-gradient-to-r from-gray-100 to-gray-200 hover:from-indigo-100 hover:to-purple-100 text-gray-700 hover:text-indigo-700 rounded-xl transition-all duration-200 text-sm xs:text-base font-medium shadow-sm hover:shadow-md"
        >
          <span className="whitespace-nowrap">← 构建场景</span>
        </button>
        
        <div className="flex items-center gap-2">
          <button
            onClick={toggleFavorite}
            className="p-2.5 xs:p-3 bg-gradient-to-r from-yellow-100 to-orange-100 hover:from-yellow-200 hover:to-orange-200 text-yellow-600 hover:text-yellow-700 rounded-xl transition-all duration-200 shadow-sm hover:shadow-md"
            title="收藏场景"
          >
            <FiStar size={16} className="xs:w-4 xs:h-4 sm:w-5 sm:h-5" />
          </button>
          
          <button
            onClick={regenerateScene}
            disabled={state.isGeneratingScene}
            className="p-2.5 xs:p-3 bg-gradient-to-r from-blue-100 to-indigo-100 hover:from-blue-200 hover:to-indigo-200 text-blue-600 hover:text-blue-700 rounded-xl transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
            title="重新生成场景"
          >
            <FiRefreshCw size={16} className={`xs:w-4 xs:h-4 sm:w-5 sm:h-5 ${state.isGeneratingScene ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </motion.div>

      {/* 场景信息 */}
      <motion.div 
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="text-center space-y-1.5 xs:space-y-2"
      >
        <h2 className="text-xl xs:text-2xl sm:text-2xl font-bold text-gray-800">{state.currentScene.title}</h2>
        <p className="text-sm xs:text-base text-gray-600">{state.currentScene.description}</p>
      </motion.div>

      {/* 交互式图片 */}
      <motion.div 
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 0.2 }}
        className="relative bg-white rounded-xl shadow-lg overflow-hidden"
      >
        {/* 占位图片 */}
        <div className="relative w-full h-64 xs:h-80 sm:h-96 bg-gradient-to-br from-purple-100 via-blue-100 to-green-100 flex items-center justify-center">
          <div className="text-center px-4">
            <div className="text-4xl xs:text-5xl sm:text-6xl mb-2 xs:mb-4">🌄</div>
            <p className="text-base xs:text-lg sm:text-lg text-gray-600">包含单词的 AI 生成圼景</p>
            <p className="text-xs xs:text-sm sm:text-sm text-gray-500 mt-1 xs:mt-2">点击下方的单词标签进行交互学习</p>
          </div>
          
          {/* 单词热点 */}
          {state.currentScene.hotspots.map((hotspot) => (
            <motion.button
              key={hotspot.id}
              initial={{ opacity: 0, scale: 0 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.5 + (parseInt(hotspot.id.split('-')[1]) * 0.1) }}
              onClick={() => handleHotspotClick(hotspot)}
              className={`absolute bg-white/90 backdrop-blur-sm border-2 rounded-md xs:rounded-lg px-2 xs:px-3 py-1.5 xs:py-2 font-medium text-xs xs:text-sm transition-all hover:scale-110 hover:shadow-lg ${
                selectedHotspot === hotspot.id 
                  ? 'border-purple-500 bg-purple-100 text-purple-700' 
                  : 'border-blue-300 text-blue-700 hover:border-blue-500'
              }`}
              style={{
                left: `${hotspot.x}%`,
                top: `${hotspot.y}%`,
                transform: 'translate(-50%, -50%)'
              }}
            >
              {hotspot.wordId}
            </motion.button>
          ))}
        </div>
      </motion.div>

      {/* 单词学习面板 */}
      <AnimatePresence>
        {showDefinition && currentWord && wordDefinitions[currentWord] && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="bg-white rounded-xl shadow-lg p-4 xs:p-6 space-y-3 xs:space-y-4"
          >
            <div className="flex items-center justify-between">
              <h3 className="text-xl xs:text-2xl font-bold text-purple-700">{currentWord}</h3>
              <button
                onClick={() => setShowDefinition(false)}
                className="text-gray-400 hover:text-gray-600 text-xl xs:text-2xl"
              >
                ×
              </button>
            </div>
            
            <div className="grid md:grid-cols-2 gap-4 xs:gap-6">
              {/* 左侧 - 基本信息 */}
              <div className="space-y-3 xs:space-y-4">
                <div>
                  <h4 className="font-semibold text-gray-700 mb-1.5 xs:mb-2 text-sm xs:text-base">发音</h4>
                  <div className="flex items-center gap-2">
                    <span className="text-blue-600 font-mono text-sm xs:text-base">{wordDefinitions[currentWord].pronunciation}</span>
                    <button
                      onClick={() => playWordPronunciation(currentWord)}
                      className="p-1.5 xs:p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                    >
                      <FiVolume2 size={14} className="xs:w-4 xs:h-4" />
                    </button>
                  </div>
                </div>
                
                <div>
                  <h4 className="font-semibold text-gray-700 mb-1.5 xs:mb-2 text-sm xs:text-base">词性</h4>
                  <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs xs:text-sm">
                    {wordDefinitions[currentWord].partOfSpeech}
                  </span>
                </div>
                
                <div>
                  <h4 className="font-semibold text-gray-700 mb-1.5 xs:mb-2 text-sm xs:text-base">释义</h4>
                  <p className="text-gray-600 text-sm xs:text-base">{wordDefinitions[currentWord].definition}</p>
                </div>
              </div>
              
              {/* 右侧 - 例句和练习 */}
              <div className="space-y-4">
                <div>
                  <h4 className="font-semibold text-gray-700 mb-2">例句</h4>
                  <div className="space-y-2">
                    {wordDefinitions[currentWord].examples.map((example, index) => (
                      <div key={index} className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-gray-700 italic">"{example}"</p>
                      </div>
                    ))}
                  </div>
                </div>
                
                {/* 发音练习 */}
                <div>
                  <h4 className="font-semibold text-gray-700 mb-2">发音练习</h4>
                  <button
                    onClick={() => startPronunciationPractice(currentWord)}
                    disabled={isRecording}
                    className={`
                      flex items-center gap-3 px-6 py-3 rounded-xl font-semibold transition-all duration-300 transform
                      ${isRecording 
                        ? 'bg-gradient-to-r from-red-500 to-pink-600 text-white animate-pulse shadow-lg scale-105' 
                        : 'bg-gradient-to-r from-indigo-500 to-purple-600 text-white hover:shadow-xl hover:scale-105 hover:-translate-y-1'
                      }
                    `}
                    style={{
                      boxShadow: isRecording 
                        ? '0 15px 35px -8px rgba(239, 68, 68, 0.4)' 
                        : '0 10px 25px -8px rgba(139, 92, 246, 0.4)'
                    }}
                  >
                    <FiMic size={18} />
                    <span>{isRecording ? '正在聆听您的发音...' : '开始语音练习'}</span>
                  </button>
                  
                  {/* 发音结果 */}
                  {pronunciationResults[currentWord] && (
                    <div className="mt-2 p-3 bg-blue-50 rounded-lg">
                      <p className="text-sm text-blue-700">
                        发音准确度: {pronunciationResults[currentWord].toFixed(0)}%
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 学习统计 */}
      <motion.div 
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.3 }}
        className="bg-white rounded-xl shadow-lg p-6"
      >
        <h3 className="text-lg font-semibold text-gray-800 mb-4">📊 学习轨迹</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {state.currentScene.words.map((word) => {
            const wordData = wordDefinitions[word];
            const accuracy = pronunciationResults[word] || 0;
            
            return (
              <div key={word} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="font-medium text-gray-700">{word}</div>
                <div className="text-sm text-gray-500 mt-1">
                  {wordData ? `${wordData.correctPronunciations}/${wordData.totalAttempts}` : '0/0'}
                </div>
                <div className={`text-xs mt-1 ${
                  accuracy > 90 ? 'text-green-600' : 
                  accuracy > 70 ? 'text-yellow-600' : 
                  accuracy > 0 ? 'text-red-600' : 'text-gray-400'
                }`}>
                  {accuracy > 0 ? `${accuracy.toFixed(0)}%` : '未练习'}
                </div>
              </div>
            );
          })}
        </div>
      </motion.div>
    </div>
  );
};

export default InteractiveLearning;